package com.tuyue.police.controller.vip;

import com.tuyue.police.biz.IEnterpriseBiz;
import com.tuyue.police.biz.ISectorBiz;
import com.tuyue.police.enums.ResultEnum;
import com.tuyue.police.exception.MyException;
import com.tuyue.police.pojo.Enterprise;
import com.tuyue.police.pojo.Sector;
import com.tuyue.police.util.Result;
import com.tuyue.police.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * @Author: 王金海
 * @Description: 布防图
 * @Date: Created by Administrator on 2018/3/27.
 * @Modified By:
 */
@RestController
@RequestMapping("vip/protection/")
public class ProtectionController {

    @Autowired
    private IEnterpriseBiz enterpriseBiz;
    @Autowired
    private ISectorBiz sectorBiz;

    @Value("${uploadaddress}")
    private String imgAddress;
    /**
     * 企业上传布防图
     * @param file
     * @param request
     * @param eId
     * @return
     * @throws IOException
     */
    //处理文件上传
    @PostMapping("uploadimg/{eId}")
    public Result uploadImg(@RequestParam("file") MultipartFile file,
                            HttpServletRequest request, @PathVariable Long eId) throws IOException {
        if (file.isEmpty()) {
            throw new MyException(ResultEnum.FILENULL);
        }
        //上传的文件名
        String fileName = file.getOriginalFilename();
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        // 文件上传后的路径
        // 解决中文问题，liunx下中文路径，图片显示问题UUID
        fileName = UUID.randomUUID() + suffixName;
        String filePath = request.getSession().getServletContext().getRealPath(imgAddress);
        Enterprise enterprise = enterpriseBiz.uploadImg(eId, file.getBytes(), filePath, fileName, imgAddress);
        return ResultUtil.success(enterprise);
    }


    /**
     * 设置防区位置
     * @param sectors
     * @return
     */
    @PostMapping("setting")
    public Result setting(@RequestBody Sector[] sectors){
        for (Sector sector : sectors) {
            if (sector.getSectorId()==0) {
                throw new MyException(ResultEnum.SECTOR_NOTNULL);
            }
        }
        List<Sector> sectorList = sectorBiz.settingSector(sectors);
        return ResultUtil.success(sectorList);
    }

    /**
     * 根据企业ID查询防区列表（中间跳过设备）
     * @param eId
     * @return
     */
    @GetMapping("findSector/{eId}")
    public Result findSector(@PathVariable Long eId){
        List<Sector> listDefenceArea = sectorBiz.findListSector(eId);
        return ResultUtil.success(listDefenceArea);
    }
}
